import React, { Component } from 'react'
import AMapLoader from '@amap/amap-jsapi-loader'
import fetch, { Headers } from 'node-fetch'
import { observer, inject } from 'mobx-react'
import ReactDOMServer from 'react-dom/server'
import { Link, withRouter } from 'react-router-dom'

import { toJS, computed } from 'mobx'
import { get } from 'lodash'
import { Panel, Card } from 'components/Base'
import ComponentMonitoringStore from 'stores/monitoring/component'
import styles from './index.scss'
import { dict } from '../ClusterNodes/NodesTop5'

@observer
class Map extends Component {
  constructor(props) {
    super(props)
    this.map = {}
    const cluster = props.cluster
    this.componentMonitoringStore = new ComponentMonitoringStore({
      cluster,
    })
    this.fetchData()
  }

  fetchData = () => {
    this.componentMonitoringStore.fetchHealthMetrics()
  }

  @computed
  get componentHealth() {
    return toJS(this.componentMonitoringStore.health)
  }

  async getLocation() {
    const myHeaders = new Headers()
    // myHeaders.append("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)");
    myHeaders.append('Accept', '*/*')
    myHeaders.append('Host', '10.101.165.43:9092')
    myHeaders.append('Connection', 'keep-alive')
    myHeaders.append('Access-Control-Allow-Origin', '*')

    const requestOptions = {
      method: 'GET',
      headers: myHeaders,
      mode: 'cors',
      redirect: 'follow',
    }
    let data
    await fetch('http://10.101.165.43:9092/getAllNodeInfos', requestOptions)
      .then(response => {
        data = response.json()
        return data // 返回的data传入下一个then的result参数
      })
      .then(result => {
        data = result
      })
      .catch(error => console.log('error', error))
    // console.log(data) // 数据库数据

    return data
  }
  // markerEvent在创建点标记后调用，这里不写了

  // 2.dom渲染成功后进行map对象的创建
  async componentDidMount() {
    AMapLoader.load({
      key: '6059e663a889790330dddcfee55d3a89', // 申请好的Web端开发者Key，首次调用 load 时必填
      verson: '2', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.TileLayer'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then(async AMap => {
        this.map = new AMap.Map('container', {
          // 设置地图容器id
          viewMode: '3D', // 是否为3D地图模式
          // pitch: 75, // 地图俯仰角度，有效范围 0 度- 83 度
          zoom: 10, // 初始化地图级别
          center: [116.358, 39.961], // 初始化地图中心点位置
          mapStyle: 'amap://styles/macaron',
        })

        const data = await this.getLocation()
        // 创建自定义信息窗体
        const CustomInfoWindow = ({ title, content }) => {
          return (
            <div className={styles.customwindow}>
              <div className={styles.windowTitle}>{title}</div>
              <div className={styles.windowContent}>{content}</div>
            </div>
          )
        }
        // const [showPage, setShowPage] = useState(false);
        for (const edge_node in data) {
          // edge_node取值0，1，2...
          const node_name = data[edge_node].name
          const node_ip = data[edge_node].ip
          const node_cpu = data[edge_node].cpu
          const node_memory = ((data[edge_node].memory * 100) / 100).toFixed(2)
          const LAT = data[edge_node].geom[0]
          const LNG = data[edge_node].geom[1]
          let node_status = '运行中' // 1表示节点正常运行，0表示告警
          for (const node in dict) {
            if (node == node_name) {
              node_status = dict[node] == undefined ? '告警' : '运行中'
            }
          }
          let node_marker = ''
          if (node_status == '告警') {
            node_marker =
              'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
            // node_marker = 'https://a.amap.com/jsapi_demos/static/images/red.png'
          } else {
            node_marker =
              'https://a.amap.com/jsapi_demos/static/images/green.png'
          }
          const marker1 = new AMap.Marker({
            position: new AMap.LngLat(LAT, LNG),
            icon: new AMap.Icon({
              image: node_marker,
            }),
          })

          this.map.add(marker1)
          const Content = (
            <div>
              <div>{`ip地址: ${node_ip}`}</div>
              <div>{`CPU: ${node_cpu} 核`}</div>
              <div>{`内存：${node_memory} GB`}</div>
              <div>{`状态：${node_status}`}</div>
            </div>
          )
          const customInfoWindow = new window.AMap.InfoWindow({
            isCustom: true, // 使用自定义窗体
            content: ReactDOMServer.renderToString(
              <CustomInfoWindow
                title={`节点名称: ${node_name}`}
                content={Content}
              />
            ),

            // size: new window.AMap.Size(200, 100),
            autoMove: true,
            offset: new window.AMap.Pixel(0, -30),
          })

          // 添加鼠标移入事件
          marker1.on('mouseover', () => {
            // 打开信息窗口
            customInfoWindow.open(this.map, marker1.getPosition())
          })

          // 添加鼠标移出事件
          marker1.on('mouseout', () => {
            // 关闭信息窗口s
            customInfoWindow.close()
          })

          // 添加点击事件
          window.AMap.event.addListener(marker1, 'click', () => {
            this.props.history.push(`/clusters/default/nodes/${node_name}`)
          })
        }
        // 设置要素
        this.map.setFeatures(['bg', 'road', 'building', 'water'])
      })

      .catch(e => {
        console.log(e)
      })
  }

  render() {
    const { counts, isLoading = false } = this.componentHealth
    const { health = 0, total = 0 } = counts.node || {}
    // console.log(Object.keys(dict).length)

    // 1.初始化创建地图容器,div标签作为地图容器，同时为该div指定id属性；
    return (
      <Card className={styles.map}>
        <div className={styles.title}>节点地理信息</div>

        <div className={styles.App}>
          在线节点数：{health} &nbsp;&nbsp;&nbsp; 总节点数：{total}
        </div>
        {/* <div className={styles.header}>
          <div>{'节点地理信息'}</div>
        </div> */}

        {/* <div id="container" className="map" style={{ height: '40%' }}></div> */}
        <div style={{ height: '440px' }}>
          <div id="container" className="map" style={{ height: '100%' }} />
        </div>
      </Card>
    )
  }
}
// 导出地图组建类
export default withRouter(Map)
